package cn.edu.sysu.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import cn.edu.sysu.util.Transaction;

import com.mysql.jdbc.Driver;

public enum TransactionRead implements Transaction {

	INSTANCE;

	private Connection connection;

	@Override
	public void begin() {
		try {
			if (connection == null || !isActive()) {
				Driver driver = (Driver)Class.forName(CONSTANT.MYSQL_DRIVER).newInstance();
				connection = DriverManager.getConnection(CONSTANT.getDBReadURL(), CONSTANT.DBUSER, CONSTANT.DBPASS);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void commit() throws TransactionException {

	}

	@Override
	public void rollback() throws TransactionException {

	}

	@Override
	public boolean isActive() throws TransactionException {
		try {
			if (connection != null && connection.isClosed()) {
				connection = null;
				return false;
			}
		} catch (SQLException e) {
			throw new TransactionException(e);
		}

		return true;
	}

	@Override
	public void preDestroy() {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
	}

	@Override
	public <T> T getResource(Class<T> klass) {
		if (klass.equals(Connection.class)) {
			@SuppressWarnings("unchecked")
			T con = (T)connection;

			return con;
		}

		throw new IllegalArgumentException();
	}

}
